using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenCvSharp;
using Point = OpenCvSharp.Point;

namespace PddWebAuto
{
    /// <summary>
    /// 滑块验证
    /// </summary>
    public class SliderVerify
    {
        public static async Task<(bool, Point)> verify(byte[] bgB, byte[] smallB, Rectangle bgRect, Rectangle smallRect)
        {
            if (smallRect.Height > bgRect.Height)
            {
                smallRect.Height = bgRect.Height;
            }

            string bgPath = Path.GetTempFileName();
            string smallPath = Path.GetTempFileName();
            System.Diagnostics.Debug.WriteLine(bgPath);
            System.Diagnostics.Debug.WriteLine(smallPath);
            // byte[] bgB = File.ReadAllBytes(@"C:\Users\shouh\Desktop\slider-bg.jpg");
            // byte[] smallB = File.ReadAllBytes(@"C:\Users\shouh\Desktop\block.jpg");
            File.WriteAllBytes(bgPath, bgB);
            File.WriteAllBytes(smallPath, smallB);

            await TaskHelper.Delay(200);

            Mat Bg = new Mat(bgPath, ImreadModes.Color);
            Mat slide = new Mat(smallPath, ImreadModes.Color);

            //Mat BgImage = Bg;
            //Mat slideImage = slide;
            Mat BgImage = new Mat();
            Mat slideImage = new Mat();
            Cv2.Resize(Bg, BgImage, new OpenCvSharp.Size(bgRect.Width, bgRect.Height), 0, 0);
            Cv2.Resize(slide, slideImage, new OpenCvSharp.Size(smallRect.Width, smallRect.Height), 0, 0);

            Mat BgCanny = new Mat();
            Cv2.Canny(BgImage, BgCanny, 200, 310);
            Mat BgRGB = new Mat();
            Cv2.CvtColor(BgCanny, BgRGB, ColorConversionCodes.GRAY2RGB);
            Mat slideCanny = new Mat();
            Cv2.Canny(slideImage, slideCanny, 200, 310);
            Mat slideRGB = new Mat();
            Cv2.CvtColor(slideCanny, slideRGB, ColorConversionCodes.GRAY2RGB);
            Mat result = new Mat();
            Cv2.MatchTemplate(BgRGB, slideRGB, result, TemplateMatchModes.CCoeffNormed);
            //数组位置下x,y
            Point minLoc = new Point(0, 0);
            Point maxLoc = new Point(0, 0);
            Point matchLoc = new Point(0, 0);
            Cv2.MinMaxLoc(result, out minLoc, out maxLoc);
            matchLoc = maxLoc;
            Bg.Dispose();
            slide.Dispose();
            BgImage.Dispose();
            slideImage.Dispose();
            BgCanny.Dispose();
            BgRGB.Dispose();
            slideCanny.Dispose();
            slideRGB.Dispose();
            result.Dispose();
            bgB = new byte[0];
            smallB = new byte[0];
            if (matchLoc.X < 10)
            {
                return (false, default);
            }

            return (true, matchLoc);
        }
    }
}